package com.cmdi.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cmdi.domain.R;
import com.cmdi.domain.SysPrivilege;
import com.cmdi.log.annotation.SysLog;
import com.cmdi.service.SysPrivilegeService;
import com.cmdi.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * @Description: 权限操作
 * @Author: gaozb
 * @Date: 2021/9/1$ 22:09$
 * @Version: 1.0
 */
@Slf4j
@RestController
@Api(tags = "权限操作")
public class SysPrivilegeController {
    @Autowired
    private SysPrivilegeService sysPrivilegeService;

    @GetMapping("/getprivilege")
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    @ApiOperation("分页获取权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="current", value = "当前页", required = true),
            @ApiImplicitParam(name="size", value = "当前页数量，-1表示获取所有", required = true)
    })
    public R<Page<SysPrivilege>> findByPage(Page<SysPrivilege> page){
        // 添加排序规则，按照修改时间
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<SysPrivilege> privilegePage = sysPrivilegeService.page(page);
        return R.ok(privilegePage);
    }

    @GetMapping("/getprivilege2")
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    @ApiOperation("分页获取权限列表，近获取当前用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name="current", value = "当前页", required = true),
            @ApiImplicitParam(name="size", value = "当前页数量，-1表示获取所有", required = true)
    })
    @SysLog("获取权限列表")
    public R<Page<SysPrivilege>> findByPage2(HttpServletRequest request,
                                             @RequestParam("current") Integer current,
                                             @RequestParam("size") Integer size) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        Integer userIdFromtoken = JwtUtil.getUserIdFromtoken(token.replace("bearer ", ""));
        log.info("用户id:{}", userIdFromtoken);
        if(userIdFromtoken == -1) {
            return R.fail("用户错误");
        }
        Page<SysPrivilege> page = new Page<SysPrivilege>(current, size);
        Page<SysPrivilege> privilegePage = sysPrivilegeService.queryPrivilege(page, userIdFromtoken);
        return R.ok(privilegePage);
    }

    @GetMapping("/getprivilege3")
    @PreAuthorize("hasAuthority('sys_privilege_query')")
    @ApiOperation("分页获取权限列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="current", value = "当前页", required = true),
            @ApiImplicitParam(name="size", value = "当前页数量，-1表示获取所有", required = true),
            @ApiImplicitParam(name="id", value = "用户id", required = true)
    })
    public R<Page<SysPrivilege>> findByPage3(@RequestParam("current") Integer current,
                                             @RequestParam("size") Integer size,
                                             @RequestParam("id") int id){
        Page<SysPrivilege> page = new Page<SysPrivilege>(current, size);
        QueryWrapper<SysPrivilege> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("last_update_time");
        Page<SysPrivilege> privilegePage = sysPrivilegeService.page(page, queryWrapper);
        return R.ok(privilegePage);
    }

    @PostMapping("/addprivilege")
    @PreAuthorize("hasAuthority('sys_privilege_add')")
    @ApiOperation("新增权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="sysPrivilege", value = "SysPrivilege-Json", required = true)
    })
    public R<SysPrivilege> addPrivilege(@RequestBody @Validated SysPrivilege sysPrivilege, Principal principal){
        String username = principal.getName();
        sysPrivilege.setUrl(username);
        sysPrivilegeService.save(sysPrivilege);
        return R.ok(sysPrivilege, "add ok");
    }

    @PostMapping("/updateprivilege")
    @PreAuthorize("hasAuthority('sys_privilege_update')")
    @ApiOperation("修改权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="sysPrivilege", value = "SysPrivilege-Json", required = true)
    })
    public R updatePrivilege(@RequestBody @Validated SysPrivilege sysPrivilege, Principal principal) {
        if(sysPrivilege.getId() == null) {
            return R.fail("id is null");
        }
        String username = principal.getName();
        sysPrivilege.setUrl(username);
        boolean b = sysPrivilegeService.updateById(sysPrivilege);
        return b ? R.ok(null, "update ok") : R.fail("no update");
    }

    @GetMapping("/deleteprivilege")
    @PreAuthorize("hasAuthority('sys_privilege_delete')")
    @ApiOperation("删除权限")
    @ApiImplicitParams({
            @ApiImplicitParam(name="sysPrivilege", value = "SysPrivilege-Json", required = true)
    })
    public R<SysPrivilege> updatePrivilege(@RequestParam(name = "id", required = true) Long id) {
        boolean b = sysPrivilegeService.removeById(id);
        return b ? R.ok(null, "delete ok") : R.fail("no delete");
    }
}